import axios from "axios";
import store from '@/store/'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router/index' //导入路由

export const defUrl = 'http://localhost:5249/';
export const loginUrl = () => "http://localhost:5050/";
export const apiUrl = `${defUrl}api/`;
const service = axios.create({
  baseURL: `${apiUrl}`
});

/*
 * 请求拦截器
 *    发送请求时的处理
 */
service.interceptors.request.use(config => {
  var token = store().accessToken;
  //配置axios，请求时带上Token
  config.headers.Authorization = `Bearer ${token}`;

  return config;
});

/*
* 响应拦截器
*    接收到数据的处理
*/
service.interceptors.response.use(async res => {
  let { data, success, message, otherSource } = res.data;
  //错误码判断
  if (success === false && otherSource === 401) {
    /* //刷新Token
    var refreshToken = store().refreshToken;
    const response = await axionRefreshToken(refreshToken);
    if (response.success) {
      mainStore().$patch({
        accessToken: response.data,
        refreshToken: response.otherSource
      });

      service.defaults.headers.common['Authorization'] = `Bearer ${data}`;

      return service(response.config);
    } else {
      router.push('/login');
    } */

    router.push('/login');
  } else if (success === false && otherSource === 403) {
    //没有权限
    ElMessage({
      message: message,
      type: 'warning',
    });
  }

  return res
}, err => {
  return Promise.reject(err)
});

const axionRefreshToken = async (refreshToken) => {
  const myAxios = axios.create({
    baseURL: loginUrl() + "api/",
  });

  myAxios.defaults.headers.common['Authorization'] = `Bearer ${refreshToken}`;

  let {data} = await myAxios.get("Account");
  console.log(data);

  return data;
}

export default service